package argo.hot100.arr;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class Merge {
    public int[][] merge(int[][] intervals) {
        if (intervals == null || intervals.length <= 1) {
            return intervals;
        }

        List<int[]> res = new ArrayList<>();

        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] - o2[0];
            }
        });
        int[] pre = null, cur = null;
        for (int i = 1; i < intervals.length; i++) {
            pre = intervals[i - 1];
            cur = intervals[i];
            if (pre[1] < cur[0]) {
                res.add(pre);
            } else {
                cur[0] = pre[0];
                cur[1] = Math.max(cur[1], pre[1]);
            }
        }
        res.add(cur);


        return res.toArray(new int[res.size()][]);
    }

}
